package com.gjq.springboot.utils;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;


public class CommandUtil {

//    public static void main(String[] args) throws Exception {
//
//        System.out.println("ok1");
//        // win
////        String str=CommandUtil.winCmd("ipconfig");
////        System.out.println(str);
//
//        // linux
//        String str = CommandUtil.linuxCmd("setenforce 0");
//        System.out.println(str);
//        System.out.println(CommandUtil.linuxCmd("yum install -y vsftpd"));
//
//        //String str=CommandUtil.linuxCmd("CommandUtil.linuxCmd("setenforce 0");");
//        //System.out.println(str);
//    }

    /**
     * win系统命令执行工具类
     */
    public static String winCmd(String cmd) {
        Process pro = null;
        String stdout="";
        try {
            pro = Runtime.getRuntime().exec(cmd);
            pro.waitFor();
            InputStream in = pro.getInputStream();
            stdout =processInputStream(in, "GBK");  // 当然 这里可以之定义编码 UTF-8 等
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pro != null){
                pro.destroy();
            }
        }
        return stdout;
    }

    /**
     * linux系统命令执行工具类
     */
    //cd /root

    public static String charset = Charset.defaultCharset().toString();
    public static String linuxCmd(String cmd) {
        // /bin/sh
        System.out.println(cmd);
        String[] StringCmds = {"/bin/sh","-c",cmd}; // 我们使用 "/bin/sh","-c" 参数的话，值可以支持linux 命令管道符号的
        Process pro = null;
        String stdout="";
        try {
            pro = Runtime.getRuntime().exec(StringCmds);
            pro.waitFor();
            InputStream in = pro.getInputStream();
            stdout =processInputStream(in, charset); // 原本这里使用这个参数的charset
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pro != null){
                pro.destroy();
            }
        }
        return stdout;
    }


    public static String processInputStream(InputStream in, String charset) throws Exception {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        String str = result.toString(charset);
        return str;
    }

}
